<script>
	import TencentCloudChat from '@tencentcloud/chat';
	import TIMUploadPlugin from 'tim-upload-plugin';
	const SDKAppID = 1600070087; // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
	let userID = null; // 您的 userID
	let userSig = ''; // 用户登录即时通信 IM 的密码，其本质是对 UserID 等信息加密后得到的密文
	import request from './utils/request'
	export default {
		globalData: {
			userInfo: null,
			token: null, //token 
			address: '', //地址
			location: {
				longitude: '',
				latitude: ''
			},
			city: '',
			imgUrl: '',
			imMessageNum: 0,
			chat: TencentCloudChat.create({
				SDKAppID
			}),
			isSDKReady:false,
			inviteId:null,
		}, 

		onLaunch: function(e) {
			console.log('App获取scene',e)
			if(e.query){
				const scene = this.getSceneParam(decodeURIComponent(e.query.scene))
				this.globalData.inviteId = scene.pid
			}
			// 11111
			this.bindTIMEvent()
			this.globalData.chat.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});
			if (uni.getStorageSync('token')) {
				this.getToken()
				this.IMLogin()
			} else {
				if(e.path!='subpages/share/share'){
					//#ifdef APP
					if(!uni.getStorageSync('showGuide')){
						uni.reLaunch({
							url: '/subpages/login/guide'
						}) 
					}else{
						uni.reLaunch({
							url: '/subpages/login/login'
						}) 
					}
					//#endif
					//#ifndef APP
					uni.reLaunch({
						url: '/subpages/login/login'
					}) 
					//#endif
				}
			}
			console.warn('当前组件仅支持 uni_modules 目录结构 ，请升级 HBuilderX 到 3.1.0 版本以上！')
			console.log('App Launch')
		},
		onShow: function() {
			// this.clearToken()
			console.log('App Show')
			//#ifdef MP-WEIXIN
				this.getOpenid()
			//#endif
			
			//更新定位
			uni.getLocation({
				type: 'gcj02',
				isHighAccuracy: true,
				success: r => {
					uni.setStorageSync("dingwei", {
						lat: r.latitude,
						lng: r.longitude
					})
					if(uni.getStorageSync('dw')){
						let dw = uni.getStorageSync('dw')
						dw.lng = r.longitude
						dw.lat = r.latitude
						uni.setStorageSync('dw',dw)
					}
				},
				fail: (err) => {
					console.log(err)
				},
				complete: () => {}
			});
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			async IMLogin() {
				this.globalData.chat.setLogLevel(1)
				console.log(this.globalData.chat)
				let signRes = await request.getData('user/getSign')
				userSig = signRes.data
				this.globalData.chat.login({
					userID,
					userSig
				}).then(res => {
					console.log('IM登录成功',res.data); // 登录成功
					if (res.data.repeatLogin === true) {
						// 标识账号已登录，本次登录操作为重复登录。
						console.log(res.data.errorInfo);
					}
				}).catch(function(imError) {
					console.warn('login error:', imError); // 登录失败的相关信息
				});
			},
			bindTIMEvent() {
				this.globalData.chat.on(TencentCloudChat.EVENT.SDK_READY, this.handleSDKReady);
				this.globalData.chat.on(TencentCloudChat.EVENT.SDK_NOT_READY, this.handleSDKNotReady);
				this.globalData.chat.on(TencentCloudChat.EVENT.KICKED_OUT, this.handleKickedOut);
			},
			// sdk ready 以后可调用 API
			handleSDKReady(event) {
				
				this.globalData.isSDKReady = true
				this.globalData.chat.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, this
					.onTotalUnreadMessageCountUpdated);
			},
			onTotalUnreadMessageCountUpdated(event) {
				this.globalData.imMessageNum = event.data
				console.log(`未读消息：${event.data}`)
				setTimeout(() => {
					uni.$emit("message_num", this.globalData.imMessageNum)
				}, 50)
			},
			handleSDKNotReady(event) {
				if (uni.getStorageSync('token')) {
					this.getToken()
					this.IMLogin()
				}
				console.log("SDK 未完成初始化 如果是退出登录可忽略")
			},
			handleKickedOut(event) {
				console.log("被踢了")
				let _this = this
				_this.clearToken()
				uni.showToast({
					title: `有人登录了你的账号。`,
					icon: "none",
					duration: 1500,
					success() {						
						setTimeout(() => {
							uni.reLaunch({
								url: "/subpages/login/login"
							})
						}, 1500)
					}
				});
			},
			getOpenid(){
				// #ifdef MP-WEIXIN
				if(!uni.getStorageSync('openid')){
					wx.login({
					  success: function(res) {
							if (res.code) {
							  request.getData("login/getOpenid",{'code':res.code}).then((res) =>{
								  uni.setStorageSync('openid',res.data.openid)
								  console.log(res.data.openid,"openid");
							  })
							}
						}
					})
				}else{
					console.log(uni.getStorageSync('openid'),"openid")
				}
				// #endif
			},
			setToken(token, userInfo) {
				this.globalData.token = token
				this.globalData.userInfo = JSON.parse(userInfo)
				userID = String(this.globalData.userInfo.id)
				uni.setStorageSync('token', token)
				uni.setStorageSync('userInfo', userInfo)
				this.IMLogin()
			},
			getToken() {
				this.globalData.token = uni.getStorageSync('token')
				this.globalData.userInfo = JSON.parse(uni.getStorageSync('userInfo'))
				userID = String(this.globalData.userInfo.id)
				return this.globalData.token
			},
			clearToken() {
				this.globalData.userInfo = null;
				this.globalData.token = null;
				uni.removeStorageSync("token");
				uni.removeStorageSync("userInfo");
				uni.removeStorageSync("role");
				this.IMLogout()
			},
			IMLogout() {
				// logout TUIKit
				this.globalData.chat.logout();
				this.globalData.imMessageNum = 0
				setTimeout(() => {
					uni.$emit("message_num", 0)
				}, 50)
			},
			// 上传图片
			uploadFile(filePath, formData = {}, callback) {
				// 多图上传
				console.log(request.requestUrl + "common/upload")
				const uploadTasks = filePath.map(item => {
					return new Promise((resolve, reject) => {
						uni.uploadFile({
							url: request.requestUrl + "common/upload",
							filePath: item, // 选择图片或视频之后返回的临时文件地址
							name: "file",
							formData,
							success: ({
								statusCode,
								data
							}) => {
								data = JSON.parse(data);
								if (statusCode == 200 && data.code == 1) {
									resolve(data.data.fullurl);
								}
							},
							fail: (error) => {
								reject(error)
							}
						})
					})
				})
				Promise.all(uploadTasks).then(res => {
					callback(res)
				})
			},
			getSceneParam(scene) {
				let str = scene.split('&')
				let obj = {}
				for(const item of str) {
					let param = item.split('=')
					obj[param[0]] = param[1]
				}
				return obj
			},
			getMyAddress(q){
				if (!q && uni.getStorageSync('dw')) {
				} else {
					var that = this
					uni.getLocation({
						type: 'gcj02',
						isHighAccuracy: true,
						success: r => {
							uni.setStorageSync("dingwei", {
								lat: r.latitude,
								lng: r.longitude
							})
							request.getData('area/getLocation', {
								longitude: r.longitude,
								latitude: r.latitude
							}).then(res => {
								if (res.code == 1) {
									var dw = {
										id: res.data.id,
										shortname: res.data.name,
										lat: r.latitude,
										lng: r.longitude
									}
									uni.setStorageSync('dw', dw)
								}
							})
						},
						fail: (err) => {
							console.log(err)
						},
						complete: () => {}
					});
				}
			},
		}
	}
</script>

<style lang="scss">
	@import "@/uni_modules/uview-ui/index.scss";
	@import "@/static/iconfont.css";
	/*每个页面公共css */
	@import '@/uni_modules/uni-scss/index.scss';
	/* #ifndef APP-NVUE */
	@import '@/static/customicons.css';

	// 设置整个项目的背景色
	page {
		background-color: #f5f5f5;
	}

	/* #endif */
	.share {
		padding: 0;
		margin: 0;
		background-color: transparent;
	
		&::after {
			display: none;
		}
	}
	.example-info {
		font-size: 14px;
		color: #333;
		padding: 10px;
	}

	.wx-btn {
		margin: 0;
		padding: 0;
		background-color: transparent;
		line-height: initial;
		border-radius: 0;
		border: none;
		display: flex;
		justify-content: center;
		align-items: center;

		&::after {
			border: none;
		}

		&:hover {
			background-color: transparent;
		}
	}
	.flex{
		display: flex;
		flex-wrap: wrap;
	}
	.y_center{
		display: flex;
		flex-direction: column;
		align-items: center;
		/* justify-content: center; */
	}
	/* 两端对齐 */
	.flex_lr{
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	/* 平均分布 */
	.flex_pj{
		display: flex;
		justify-content: space-around;
		align-items: center;
	}
	/* 上下两端 */
	.flex_ud{
		display: flex;
		justify-content: space-between;
		flex-direction: column;
	}
	/* 中心对齐 */
	.flex_center{
		display: flex;
		justify-content:center;
		align-items: center;
	}
	.flex_row {
		display: flex;
		flex-direction: row;
		align-items: center;
	}
</style>